<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class FormWidget {

    //var $CI;
    var $debug = true;
    #configuration
    var $method = 'post';
    var $formName ;
    var $data = array();
    
    #fields
    var $fields = array() ;
    var $validators =array() ;
    
    #formatters
    var $formFormater ="<dl>{%s%}</dl>";
    var $fieldRowFormater = "<dt>{%error%}</dt><dd><label>{%label%}</label>{%field%}</dd>";


    function formwidget($formname = "myForm", $data = array()) {

        echo ($this->debug)? 'Loading Form Widget Library...' :'';
        //$this->CI =& get_instance();
        //$this->CI->load->helper(array('form', 'url'));
        require_once APPPATH.'libraries/system/FormInputWidget.php';
      //  $this->CI->load->library('form_validation');


        $this->formName = (!empty($formname))?$formname:'myForm';
        $this->data = (!empty($data))?$data:array();

    }#end of function

    /*
	* binds the data to individual form fields.
    */
    function bind($data = array()) {
        return true;
    }

    function addFields($fieldname,$type,$default='',$datasource=''){
        $field = new FormInputWidget(array('type'=>$type,'label'=>$fieldname,'default'=>$default,'data_source'=>$datasource,'extras' => array('name'=>$fieldname)));
       // print_r($field);
        array_push($this->fields, $field);
    }

    function render() {
        $elements='';
        $html= '';
        $html .="<form name='{$this->formName}' method='{$this->method}' >";
        foreach($this->fields as $field) {
//print_r($field);
            $elements .= $field->render($this->fieldRowFormater);
        }
        $find = array('/\{\%s\%\}/');
        $replace = array($elements);
        //print_r($this);
        $html .= preg_replace($find,$replace,$this->formFormater);

        $html .="</form>";

        return $html;
    }#end of function



}#end of class



/* -- INTERFACES -- */

interface iFormField{
	//function setBaseModel(){/* Model name to bind this field.*/}
	function setLabel();
	function getLabel();
	function setAttributes();
	function getAttributes();
	function setDefault();
	function setValidator();
	function getValidator();
}

interface iFormWidget {

	function setFormFields(array $fieldnames);

	function getFormFields();

	function setValidators(array $fieldnames);

	function setDefaults(array $fieldNames);

	/* sets the labels of the fields.*/
	function setlabels(array $fieldNames);

	function render();

	/* skips the fields from rendering*/
	function skipFields(array $fieldNames);

	function validate();

	/* Merges form to One-to-one relationship
	* @form is the form Class to join
	*/
	function merge($form);

	/* Merges form to One-to-many relationship
	 * @form is the form Class to join
	 * @count is the number of times to add a form Class
	*/
	function mergeMultiple($form,$count);

}



